/*
 * @Author: silence
 * @Date: 2023-03-18 11:08:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-03-08 16:03:08
 * @Description: 
 */
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sil_utils_package/log/SilLog.dart';
import 'package:sil_utils_package/tools/SilTools.dart';

import '../../../../entities/LangEntity.dart';
import '../LanguageController.dart';

LangEntity? LangOf(BuildContext context) {
  return Localizations.of<SilLocalizations>(context, SilLocalizations)?.lang;
}

class SilLocalizations {
  /// 当前语言
  final String localeName;
  final String? scriptCode;
  SilLocalizations(this.localeName, [this.scriptCode]);

  /// 语言列表
  static Map<String, String> languageMap = {
    'zh': '简体中文',
    'hk': '繁體中文',
    'en': 'English',
    'de': 'Deutsch', //德语
    'et': 'Eesti', //爱沙尼亚语
    'ru': 'Русский', //俄语
    'hu': 'Magyar', //匈牙利语
    'cs': 'Čeština', //捷克语
    'ro': 'România', //罗马尼亚语
    'bg': 'Български', //保加利亚语
  };

  /// 接口对应的语言列表
  static Map<String, String> languageApiMap = {
    '简体中文': 'zh',
    '繁體中文': 'hk',
    'English': 'en',
    'Deutsch': 'de', //德语
    'Eesti': 'as', //爱沙尼亚语
    'Русский': 'er', //俄语
    'Magyar': 'xyl', //匈牙利语
    'Čeština': 'jk', //捷克语
    'România': 'ro', //罗马尼亚语
    'Български': 'bg', //保加利亚语
  };

  /// 支持的语言列表
  static List<Locale> get supportedLocales {
    List<Locale> localList = [];
    Map<String, String> languageMap = SilLocalizations.languageMap;

    languageMap.forEach((key, value) {
      if (key == 'zh') {
        localList.add(Locale.fromSubtags(
            languageCode: 'zh', scriptCode: 'Hans', countryCode: '简体中文'));
      } else if (key == 'hk') {
        localList.add(Locale.fromSubtags(
            languageCode: 'zh', scriptCode: 'Hant', countryCode: '繁體中文'));
      } else {
        localList
            .add(Locale.fromSubtags(languageCode: key, countryCode: value));
      }
    });

    return localList;
  }

  /// 获取当前支持的语言
  static Locale? curSupportedLocale() {
    // 用户设置语言，如果为空，则使用系统语言
    String? settedLang = LanguageController.userSettedLang;
    return getSupportedLocales(settedLang);
  }

  /// 获取当前应该显示的语言
  /// 1如果用户设置了，就是用设置的语言
  /// 2如果没有设置就使用系统语言，如果系统语言不在支持的语言列表中，默认使用英文
  static Locale? localeResolutionCallback(
      Locale? local, Iterable<Locale> list) {
    SilLog.d('当前系统语言：${local?.languageCode},支持的语言列表：$list');

    // 1用户设置语言，如果为空，则使用系统语言
    String? settedLang = LanguageController.userSettedLang;
    Locale? settedLocale = SilLocalizations.getSupportedLocales(settedLang);

    //2如果没有设置就使用系统语言，如果系统语言不在支持的语言列表中，默认使用英文
    if (settedLocale == null) {
      String languageCode = local?.languageCode ?? 'en';
      List list = SilLocalizations.languageMap.keys.toList();
      bool isSupported = list.contains(languageCode);
      if (isSupported == false) {
        settedLocale = Locale.fromSubtags(languageCode: 'en');
      } else {
        settedLocale = Locale.fromSubtags(
            languageCode: languageCode, scriptCode: local?.scriptCode);
      }
    }

    /// 设置当前系统语言
    LanguageController.curSystemLanguageCode = settedLocale.languageCode;
    if (local?.scriptCode == 'Hant') {
      // 繁体中文
      LanguageController.curSystemLanguageCode = 'hk';
    }

    return settedLocale;
  }

  /// 从支持列表中，获取当前支持的语言
  static Locale? getSupportedLocales(String? languageCode) {
    Locale? locale;
    Map map = SilLocalizations.languageMap;

    if (languageCode == "zh") {
      locale = Locale.fromSubtags(
          languageCode: 'zh', scriptCode: 'Hans', countryCode: '简体中文');
    } else if (languageCode == "hk") {
      locale = Locale.fromSubtags(
          languageCode: 'zh', scriptCode: 'Hant', countryCode: '繁體中文');
    } else {
      map.forEach((key, value) {
        if (key == languageCode) {
          locale = Locale.fromSubtags(languageCode: key, countryCode: value);
          return;
        }
      });
    }

    return locale;
  }

  /// 语言数据实体
  LangEntity lang = LangEntity();
  Map langMap = Map();

  static const SilLocalizationsDelegate delegate = SilLocalizationsDelegate();

  static SilLocalizations? of(BuildContext context) {
    return Localizations.of<SilLocalizations>(context, SilLocalizations);
  }

  /// 加载本地语言数据
  Future<void> loadLocalLangData() async {
    String language = this.localeName;
    if (this.scriptCode != null) {
      language = '${language}-${this.scriptCode}';
    }

    // 根据当前语言，找到语言json文件
    String filename = "json/${language}.json";
    String jsonString = await rootBundle.loadString(filename);

    if (SilTools.stringIsEmpty(jsonString)) {
      SilLog.i('语言${language}的文件丢失了');
    }

    // 转成map
    Map<String, dynamic> langMap = jsonDecode(jsonString);
    this.langMap = langMap;
    // SilEntityLog.log('LanguageEntity', langMap);
    this.lang = LangEntity.fromJson(langMap);
  }
}

class SilLocalizationsDelegate extends LocalizationsDelegate<SilLocalizations> {
  const SilLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    List list = SilLocalizations.languageMap.keys.toList();
    return list.contains(locale.languageCode);
  }

  @override
  Future<SilLocalizations> load(Locale locale) async {
    String languageCode = locale.languageCode;

    /// 情况1，如果是不支持的语言，默认显示英文
    List list = SilLocalizations.languageMap.keys.toList();
    bool isSupported = list.contains(languageCode);
    if (isSupported == false) {
      languageCode = 'en';
    }

    ///情况2 oppo机型 scriptCode返回为空
    String? scriptCode = locale.scriptCode;
    // 处理中文，如果没有给scriptCode时的处理
    if (locale.languageCode == 'zh') {
      if (locale.scriptCode == null) scriptCode = 'Hans';
    }

    SilLocalizations silLocalizations =
        SilLocalizations(languageCode, scriptCode);
    await silLocalizations.loadLocalLangData();
    return silLocalizations;
  }

  @override
  bool shouldReload(covariant LocalizationsDelegate<SilLocalizations> old) {
    return false;
  }
}
